import React, { useState, useEffect } from "react";
import Dropdown from "rc-dropdown";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import {
  getTimeRangeTextInner,
  getTimeMarkValueType,
  transTimeValueStringToTimestamp,
} from "./utils";
import {
  DEFAULT_PRESET_ITEMS_DATA,
  DEFAULT_RELATIVE_ITEMS_DATA,
  DEFAULT_DURATION_UNIT_OPTIONS,
} from "./constant";
import classNames from "classnames";
import RelativeTime from "./components/RelativeTime";
import AbsoluteTime from "./components/AbsoluteTime";
import { useStyles } from "./style";
import { CaretDown } from "@ct0/icons";
import { Timestamp, PresetValue, DurationUnitOption } from "./type";
import classnames from "classnames";

dayjs.extend(duration);

interface TimeRangeProps {
  value?: string; // iso string | 时间戳范围string, 例如"1656653541857/1657171941857"
  defaultValue?: string;
  relativeItems?: string[]; //isoDurationString
  presetItems?: PresetValue[];
  onChange?: (value: string, timestamp: Timestamp) => void;
  getPopupContainer?: (triggerNode: HTMLElement) => HTMLElement;
  placement?:
    | "bottomLeft"
    | "bottomCenter"
    | "bottomRight"
    | "topLeft"
    | "topCenter"
    | "topRight";
  disabled?: boolean;
  durationUnitOptions?: DurationUnitOption[];
}

enum TabKey {
  RELATIVE = 0,
  ABSOLUTE = 1,
}

TimeRangePicker.transTimeValueStringToTimestamp =
  transTimeValueStringToTimestamp;

function TimeRangePicker({
  value,
  defaultValue,
  onChange,
  relativeItems,
  presetItems,
  getPopupContainer,
  placement,
  disabled = false,
  durationUnitOptions = DEFAULT_DURATION_UNIT_OPTIONS,
}: TimeRangeProps) {
  const classes = useStyles();
  const [timeMark, setTimeMark] = useState<string | undefined>();
  const [timeRangeVisible, setTimeRangeVisible] = useState<boolean>(false);
  const [activeKey, setActiveKey] = useState<TabKey>(TabKey.RELATIVE);

  const relativeTimeItems = {
    relativeItemsData: relativeItems || DEFAULT_RELATIVE_ITEMS_DATA,
    presetItemsData: presetItems || DEFAULT_PRESET_ITEMS_DATA,
  };

  const handleTabClick = (key: TabKey) => setActiveKey(key);

  const handleConfirm = (value: string, timestamp: Timestamp) => {
    setTimeMark(value);
    setTimeRangeVisible(false);
    onChange && onChange(value, timestamp);
  };

  const handleVisible = () => {
    if (disabled) {
      return;
    }
    setTimeRangeVisible(!timeRangeVisible);
  };

  const handleVisibleChange = (v: boolean) => {
    setTimeRangeVisible(v);
    v && setActiveKey(TabKey.RELATIVE);
  };
  useEffect(() => {
    const initialValue = value ?? defaultValue;
    if (initialValue) {
      // 判断初始化数据是否为有效的字符串
      const initialValueType = getTimeMarkValueType(
        initialValue,
        relativeTimeItems.presetItemsData
      );
      setTimeMark(initialValueType ? initialValue : undefined);
    } else {
      setTimeMark(undefined);
    }
  }, [value]);

  const tabContent = [
    {
      key: TabKey.RELATIVE,
      title: "相对时间",
      content: (
        <RelativeTime
          timeMark={timeMark}
          handleConfirm={handleConfirm}
          relativeItemsData={relativeTimeItems.relativeItemsData}
          presetItemsData={relativeTimeItems.presetItemsData}
          durationUnitOptions={durationUnitOptions}
        />
      ),
    },
    {
      key: TabKey.ABSOLUTE,
      title: "绝对时间",
      content: (
        <AbsoluteTime timeMark={timeMark} handleConfirm={handleConfirm} />
      ),
    },
  ];

  const activeContent = tabContent.find((t) => t.key === activeKey)?.content;

  const visible = disabled ? false : timeRangeVisible;

  return (
    <Dropdown
      trigger={["click"]}
      visible={visible}
      onVisibleChange={handleVisibleChange}
      getPopupContainer={getPopupContainer}
      placement={placement}
      overlay={
        visible ? (
          <div className={classes.customTab} role="overlay">
            <div className={classes.tabHead}>
              {tabContent.map((tab) => {
                return (
                  <span
                    className={classNames(
                      classes.tab,
                      activeKey === tab.key && classes.active
                    )}
                    onClick={() => handleTabClick(tab.key)}
                    key={tab.key}
                  >
                    {tab.title}
                  </span>
                );
              })}
            </div>
            <div className={classes.tabContent}>{activeContent}</div>
          </div>
        ) : (
          <div />
        )
      }
    >
      <div
        onClick={handleVisible}
        className={classnames(classes.trigger, {
          [classes.disabled]: disabled,
        })}
        role="trigger"
      >
        <span>
          {getTimeRangeTextInner(timeMark, relativeTimeItems.presetItemsData)}
        </span>
        <CaretDown />
      </div>
    </Dropdown>
  );
}

export default TimeRangePicker;
